package com.lry.basic.thread;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalVariableHolder1 {
    private static ThreadLocal<Integer> variableHolder = new TransmittableThreadLocal();

    public static void setValue(int val) {
        variableHolder.set(val);
    }

    public static int getValue() {
        return variableHolder.get();
    }

    public static void remove() {
        variableHolder.remove();
    }

    public static void increment() {
        variableHolder.set(variableHolder.get() + 1);
    }


    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        variableHolder.set(1);
        //线程池会复用线程，使用完线程后一定要清楚threadLocal，不然去执行新任务的时候会使用上一次的threadLocal产生错误结果
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            executor.execute(TtlRunnable.get(() -> {

                if(finalI ==0){
                    setValue(100);
                }
                long threadId = Thread.currentThread().getId();
                System.out.println("threadId: " + threadId + ", value: " + getValue()+" finalI="+finalI);

//                long threadId = Thread.currentThread().getId();
//                int before = getValue();
//                increment();
//                int after = getValue();
//                System.out.println("threadId: " + threadId + ", before: " + before + ", after: " + after);
            }));
        }

        executor.shutdown();
    }

}